package com.tarena.lbs.business.servcie.impl;

import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.dao.repository.BusinessCategoryRepository;
import com.tarena.lbs.business.dao.repository.BusinessRepository;
import com.tarena.lbs.business.dao.repository.StoreRepository;
import com.tarena.lbs.business.pojo.param.BusinessParam;
import com.tarena.lbs.business.pojo.po.BusinessCategoryPO;
import com.tarena.lbs.business.pojo.po.BusinessPO;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.query.BusinessQuery;
import com.tarena.lbs.business.pojo.vo.BusinessStoreVO;
import com.tarena.lbs.business.pojo.vo.BusinessVO;
import com.tarena.lbs.business.pojo.vo.StoreVO;
import com.tarena.lbs.business.servcie.BusinessService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BusinessServiceImpl implements BusinessService {

    private final BusinessRepository businessRepository;
    private final BusinessCategoryRepository businessCategoryRepository;
    private final StoreRepository storeRepository;

    @Autowired
    public BusinessServiceImpl(BusinessRepository businessRepository,
                               BusinessCategoryRepository businessCategoryRepository, StoreRepository storeRepository) {
        this.businessRepository = businessRepository;
        this.businessCategoryRepository = businessCategoryRepository;
        this.storeRepository = storeRepository;
    }
    public PageResult<BusinessVO> pageList(BusinessQuery query) {
        return businessRepository.pageList(query);
    }
    public void save(BusinessParam param) {
        businessRepository.save(param);
    }
    public BusinessStoreVO businessStoreDetail(Integer businessId) {
        BusinessPO businessPO = businessRepository.businessStoreDetail(businessId);
        BusinessStoreVO businessStoreVO = new BusinessStoreVO();
        BeanUtils.copyProperties(businessPO, businessStoreVO);
        // 查询行业名称
        Integer id = businessPO.getIndustryType();
        BusinessCategoryPO po = businessCategoryRepository.selectPO(id);
        if (po != null) {
            businessStoreVO.setIndustryName(po.getLabel());
        }
        // 查询旗下店铺
        List<StorePO> storePOS = storeRepository.selectByBusinessId(businessId);
        List<StoreVO> storeVOS = storePOS.stream().map(this::convertToVO).collect(Collectors.toList());
        businessStoreVO.setStoreVOList(storeVOS);
        return businessStoreVO;
    }

    private StoreVO convertToVO(StorePO storePO) {
        StoreVO storeVO = new StoreVO();
        BeanUtils.copyProperties(storePO, storeVO);
        return storeVO;
    }
}
